package com.zhiyou.aifeng.receiver

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Bundle
import cn.jpush.android.api.JPushInterface
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lzy.okgo.utils.OkLogger
import com.ruanmeng.iflytek.SpeechSynthesisHelper
import com.zhiyou.aifeng.smart_machine.MatterDetailActivity
import com.zhiyou.aifeng.smart_machine.MessageActivity
import com.zhiyou.aifeng.smart_machine.OrderDetailActivity
import io.reactivex.Flowable
import io.reactivex.schedulers.Schedulers
import org.jetbrains.anko.intentFor
import org.jetbrains.anko.newTask
import org.json.JSONException
import org.json.JSONObject


/**
 * 自定义接收器
 *
 *
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
class JPushReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {

        val bundle = intent.extras ?: return

        OkLogger.d(
            "JPush",
            "[JPushReceiver] onReceive - ${intent.action}, extras: ${printBundle(bundle)}"
        )

        when (intent.action) {
            JPushInterface.ACTION_REGISTRATION_ID -> {
                val regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID) ?: ""
                OkLogger.d("JPush", "[JPushReceiver] 接收Registration Id : $regId")
                //send the Registration Id to your server...
            }
            JPushInterface.ACTION_MESSAGE_RECEIVED -> {
                val message = bundle.getString(JPushInterface.EXTRA_MESSAGE) ?: ""
                OkLogger.d("JPush", "[JPushReceiver] 接收到推送下来的自定义消息: $message")
            }
            JPushInterface.ACTION_NOTIFICATION_RECEIVED -> {
                OkLogger.d("JPush", "[JPushReceiver] 接收到推送下来的通知")
                val notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID)
                OkLogger.d("JPush", "[JPushReceiver] 接收到推送下来的通知的ID: $notifactionId")

                val value = bundle.getString(JPushInterface.EXTRA_ALERT) ?: "您有新的消息"
                startSpeak(context, value)

                val json = JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA) ?: "{}")
                if (!json.isNull("type")) {
                    when (json.optString("type")) {
                        "work" -> {
                            val state = json.optString("workstate")
                            if (state == "1") LiveEventBus.get("orderPush").post("get")
                        }
                    }
                }
            }
            JPushInterface.ACTION_NOTIFICATION_OPENED -> {
                OkLogger.d("JPush", "[JPushReceiver] 用户点击打开了通知")

                //打开自定义的Activity
                val json = JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA) ?: "{}")
                if (!json.isNull("type")) {
                    when (json.optString("type")) {
                        "work" -> {
                            when (json.optString("workstate")) {
                                "1" -> {
                                    context.apply {
                                        startActivity(
                                            intentFor<MatterDetailActivity>(
                                                "orderId" to json.optString("bisId")
                                            ).newTask()
                                        )
                                    }
                                }
                                "5" -> {
                                    context.apply {
                                        startActivity(
                                            intentFor<OrderDetailActivity>(
                                                "orderId" to json.optString("bisId")
                                            ).newTask()
                                        )
                                    }
                                }
                            }
                        }
                        else -> {
                            context.apply {
                                startActivity(intentFor<MessageActivity>().newTask())
                            }
                        }
                    }
                } else {
                    context.apply {
                        startActivity(intentFor<MessageActivity>().newTask())
                    }
                }
            }
            JPushInterface.ACTION_RICHPUSH_CALLBACK -> {
                val extra = bundle.getString(JPushInterface.EXTRA_EXTRA) ?: ""
                OkLogger.d("JPush", "[JPushReceiver] 用户收到到RICH PUSH CALLBACK: $extra")
                //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..
            }
            JPushInterface.ACTION_CONNECTION_CHANGE -> {
                val connected =
                    intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false)
                OkLogger.w(
                    "JPush",
                    "[JPushReceiver]${intent.action} connected state change to $connected"
                )
            }
            else -> {
                OkLogger.d("JPush", "[JPushReceiver] Unhandled intent - ${intent.action}")
            }
        }
    }

    // 打印所有的 intent extra 数据
    private fun printBundle(bundle: Bundle): String {
        val sb = StringBuilder()
        loop@ for (key in bundle.keySet()) {
            when (key) {
                JPushInterface.EXTRA_NOTIFICATION_ID ->
                    sb.append("\nkey:")
                        .append(key)
                        .append(", value:")
                        .append(bundle.getInt(key))
                JPushInterface.EXTRA_CONNECTION_CHANGE ->
                    sb.append("\nkey:")
                        .append(key)
                        .append(", value:")
                        .append(bundle.getBoolean(key))
                JPushInterface.EXTRA_EXTRA -> {
                    if (bundle.getString(JPushInterface.EXTRA_EXTRA).isNullOrEmpty()) {
                        OkLogger.i("JPush", "This message has no Extra data")
                        continue@loop
                    }

                    try {
                        val json = JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA) ?: "{}")
                        val it = json.keys()

                        while (it.hasNext()) {
                            val myKey = it.next()
                            sb.append("\nkey:")
                                .append(key)
                                .append(", value: [")
                                .append(myKey)
                                .append(" - ")
                                .append(json.optString(myKey))
                                .append("]")
                        }
                    } catch (e: JSONException) {
                        OkLogger.e("JPush", "Get message extra JSON error!")
                    }

                }
                else ->
                    sb.append("\nkey:")
                        .append(key)
                        .append(", value:")
                        .append(
                            bundle.getString(key)
                        )
            }
        }
        return sb.toString()
    }

    /**
     * 语音播报
     */
    @SuppressLint("CheckResult")
    private fun startSpeak(context: Context, text: String) {
        Flowable.just(context)
            .map { SpeechSynthesisHelper.getInstance(it) }
            .subscribeOn(Schedulers.newThread())
            .observeOn(Schedulers.newThread())
            .subscribe { it.startSpeaking(text) }
    }

}
